package com.chuji.crmcj.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RadioButton;
import android.widget.TextView;

import com.chuji.crmcj.R;
import com.chuji.crmcj.utils.UIUtils;

import java.util.HashMap;

/**
 * Created by y.yiwen on 2/17/2016.
 * 自定义单选适配器
 */
public class ClientTradeAdapter extends BaseAdapter {
    private Context context;
    private String[] beans;
    HashMap<String, Boolean> states = new HashMap<String, Boolean>();//用于记录每个RadioButton的状态，并保证只可选一个

    public ClientTradeAdapter(Context context, String[] beans) {
        this.context = context;
        this.beans = beans;
    }

    @Override
    public int getCount() {
        return beans.length;
    }

    @Override
    public Object getItem(int position) {
        return beans[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.dialog_trade, null);
            holder = new ViewHolder();
            holder.tv_trade = (TextView) convertView.findViewById(R.id.tv_trade);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.tv_trade.setText(beans[position]);
        final RadioButton radio = (RadioButton) convertView.findViewById(R.id.radio_btn);
        holder.rdBtn = radio;
        //当RadioButton被选中时，将其状态记录进States中，并更新其他RadioButton的状态使它们不被选中
        holder.rdBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //重置，确保最多只有一项被选中
                for (String key : states.keySet()) {
                    states.put(key, false);
                }
                states.put(String.valueOf(position), radio.isChecked());
                UIUtils.showToastSafe("选中了" + position + "的" + beans[position]);
                ClientTradeAdapter.this.notifyDataSetChanged();
            }
        });
        boolean res = false;
        if (states.get(String.valueOf(position)) == null || states.get(String.valueOf(position)) == false) {
            res = false;
            states.put(String.valueOf(position), false);
        } else
            res = true;
        holder.rdBtn.setChecked(res);

        return convertView;
    }
    static class ViewHolder {
        TextView tv_trade;
        RadioButton rdBtn;
    }
}
